﻿using UnityEngine;
using System.Collections;
using UniLua;

namespace TCG
{
	public class CoroutineDelegate : MonoBehaviour 
	{
		private static CoroutineDelegate m_instance = null;

		public static CoroutineDelegate instance
		{
			get 
			{
				if (m_instance == null)
				{
					m_instance = new GameObject ("_TCG_CoroutineDelegate").AddComponent<CoroutineDelegate> ();
					GameObject.DontDestroyOnLoad (m_instance.gameObject);
				}
				return m_instance;
			}
		}

		public void CoroutineFrameEnd (ILuaState luaState, int luaRef)
		{
			StartCoroutine (Co_FrameEnd (luaState, luaRef));
		}

		public void CoroutineFrameNext (ILuaState luaState, int luaRef)
		{
			StartCoroutine (Co_FrameNext (luaState, luaRef));
		}

		public void CoroutineWaitingUntil (ILuaState luaState, int luaRef, float duration)
		{
			StartCoroutine (Co_WaitingUntil (luaState, luaRef, duration));
		}

		IEnumerator Co_FrameEnd (ILuaState luaState, int luaRef)
		{
			yield return new WaitForEndOfFrame ();
			luaState.RawGetI (LuaDef.LUA_REGISTRYINDEX, luaRef);
			luaState.Call (0, 0);
		}

		IEnumerator Co_FrameNext (ILuaState luaState, int luaRef)
		{
			yield return null;
			luaState.RawGetI (LuaDef.LUA_REGISTRYINDEX, luaRef);
			luaState.Call (0, 0);
		}

		IEnumerator Co_WaitingUntil (ILuaState luaState, int luaRef, float duration)
		{
			yield return new WaitForSeconds (duration);
			luaState.RawGetI (LuaDef.LUA_REGISTRYINDEX, luaRef);
			luaState.Call (0, 0);
		}
	}
}
